package com.tianyalei.wolf.sample.activity.imageload;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.tianyalei.wolf.sample.R;
import com.tianyalei.wolf.sample.imageload.ImageLoadProxy;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * 使用ImageLoader展示单张大图（如果是gif图，使用webview展示。普通的就直接展示）
 * <p>该类少做了一个处理，就是没有网时就从缓存中取值
 */
public class ImageDetailActivity extends FragmentActivity implements View.OnClickListener {

    /**
     * 展示普通图片的view（可双击放大，可缩小）
     */
    @Bind(R.id.photoview)
    PhotoView img;
    @Bind(R.id.progress)
    ProgressBar progress;
    /**
     * 底部工具栏
     */
    @Bind(R.id.ll_bottom_bar)
    LinearLayout ll_bottom_bar;
    /**
     * 顶部工具栏（返回、分享按钮）
     */
    @Bind(R.id.rl_top_bar)
    RelativeLayout rl_top_bar;
    /**
     * webview用来加载gif图片，并且设置了JS和java的调用。
     */
    @Bind(R.id.web_gif)
    WebView webView;
    public static final int ANIMATION_DURATION = 400;

    private boolean isBarShow = true;

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_detail);
        ButterKnife.bind(this);
        mContext = this;

        initData();
        String url = getIntent().getStringExtra("url");
    }

    @OnClick({R.id.img_back, R.id.img_share, R.id.tv_unlike, R.id.tv_like, R.id.img_comment, R.id.img_download})
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_share:
                break;
            case R.id.tv_like:
                break;
            case R.id.tv_unlike:
                break;
            case R.id.img_comment:
                break;
            case R.id.img_download:
                break;
        }
    }

    @JavascriptInterface
    public void img_has_loaded() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    @JavascriptInterface
    public void img_loaded_error() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    /**
     * JS控制webview里的图片点击事件
     */
    @JavascriptInterface
    public void onClick() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                toggleBar();
            }
        });
    }

    public void initData() {
        Intent intent = getIntent();
        final String url = intent.getStringExtra("url");

        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(this, "external");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                webView.loadUrl(url);
                return true;
            }

        });

        webView.setWebChromeClient(new WebChromeClient());
        webView.setBackgroundColor(Color.BLACK);

        img.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
            @Override
            public void onViewTap(View view, float x, float y) {
                toggleBar();
            }
        });

        ImageLoadProxy.displayNormalImage(this, url, img);
    }

    private void showImgInWebView(final String s) {
        if (webView != null) {
            webView.loadDataWithBaseURL("", "<!doctype html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title></title><style type=\"text/css\"> html,body{width:100%;height:100%;margin:0;padding:0;background-color:black;} *{ -webkit-tap-highlight-color: rgba(0, 0, 0, 0);}#box{ width:100%;height:100%; display:table; text-align:center; background-color:black;} body{-webkit-user-select: none;user-select: none;-khtml-user-select: none;}#box span{ display:table-cell; vertical-align:middle;} #box img{  width:100%;} </style> </head> <body> <div id=\"box\"><span><img src=\"img_url\" alt=\"\"></span></div> <script type=\"text/javascript\" >document.body.onclick=function(e){window.external.onClick();e.preventDefault(); };function load_img(){var url=document.getElementsByTagName(\"img\")[0];url=url.getAttribute(\"src\");var img=new Image();img.src=url;if(img.complete){\twindow.external.img_has_loaded();\treturn;};img.onload=function(){window.external.img_has_loaded();};img.onerror=function(){\twindow.external.img_loaded_error();};};load_img();</script></body> </html>".replace("img_url", s), "text/html", "utf-8", "");
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        toggleBar();
    }

    private void toggleBar() {
        //隐藏
        if (isBarShow) {
            isBarShow = false;
            ObjectAnimator
                    .ofFloat(ll_bottom_bar, "translationY", 0, ll_bottom_bar.getHeight())
                    .setDuration(ANIMATION_DURATION)
                    .start();
            ObjectAnimator
                    .ofFloat(rl_top_bar, "translationY", 0, -rl_top_bar.getHeight())
                    .setDuration(ANIMATION_DURATION)
                    .start();
        } else {
            //显示
            isBarShow = true;
            ObjectAnimator
                    .ofFloat(ll_bottom_bar, "translationY", ll_bottom_bar.getHeight(), 0)
                    .setDuration(ANIMATION_DURATION)
                    .start();
            ObjectAnimator
                    .ofFloat(rl_top_bar, "translationY", -rl_top_bar.getHeight(), 0)
                    .setDuration(ANIMATION_DURATION)
                    .start();
        }
    }


}
